﻿namespace YunQue.WebApi.Common.Filter
{
    /// <summary>
    /// 接口返回结果处理
    /// </summary>
    public class ResultFilterHelper
    {
        /// <summary>
        /// 格式化返回结果
        /// </summary>
        /// <param name="context"></param>
        public static void ResultHandler(ResultExecutingContext context)
        {
            object data = null;
            if (context.Result is ObjectResult objectResult)
            {
                data = objectResult.Value;
            }
            else if (context.Result is JsonResult jsonResult)
            {
                data = jsonResult.Value;
            }
            //判断 不是 ApiResultModel<T>的类型
            if (!(data is ApiResultModel<object> apiResult))
            {
                var resultWrapper = new ApiResultModel<object>
                {
                    Data = data
                };
                context.Result = new JsonResult(resultWrapper);
            }

        }
    }
    /// <summary>
    /// 异步结果过滤器
    /// </summary>
    public class ResultAsyncFilter : IAsyncResultFilter
    {
        /// <summary>
        /// 处理请求结果
        /// </summary>
        /// <param name="context"></param>
        /// <param name="next"></param>
        /// <returns></returns>
        public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
        {
            if (context.Result is ObjectResult objectResult)
            {
                // 获取返回的数据
                var originalData = objectResult.Value;

                // 检查数据是否已经是 ApiResultModel 类型
                var type = originalData?.GetType();
                if (type != null && type.IsGenericType && type.GetGenericTypeDefinition() == typeof(ApiResultModel<>))
                {
                    await next();
                    return;
                }
                // 如果不是 ApiResultModel 类型，包装成统一格式
                var apiResult = new ApiResultModel<object>
                {
                    Code = 200, // 设置状态码
                    Data = originalData, // 原始返回数据
                };

                context.Result = new ObjectResult(apiResult)
                {
                    StatusCode = objectResult.StatusCode
                };
            }
            await next.Invoke();
        }
    }
}
